import { useEffect, useState } from "react"
import { throttle } from "@/utils";


/**
 * 是否固定头部，是否显示头部
 */
export const useAffix = (Threshold = 0, flag = false) => {
  const [affix, setAffix] = useState(false);
  const [affixVisible, setaffixVisible] = useState(false);
  useEffect(() => {
    let beforeY = document.documentElement.scrollTop || window.pageYOffset || window.scrollY || document.body.scrollTop;
    const handle = throttle(() => {
      const y = document.documentElement.scrollTop || window.pageYOffset || window.scrollY || document.body.scrollTop;
      setAffix(y > Threshold);
      setaffixVisible(beforeY > y);
      setTimeout(() => {
        beforeY = y;
      }, 0)
    }, 200)
    const handle2 = () => {
      const y = document.documentElement.scrollTop || window.pageYOffset || window.scrollY || document.body.scrollTop;
      setAffix(y > Threshold);
      setaffixVisible(beforeY > y);
      setTimeout(() => {
        beforeY = y;
      }, 0)
    }
    document.addEventListener('scroll', flag ? handle2 : handle, false);
    return () => {
      document.removeEventListener("scroll", flag ? handle2 : handle, false);
    }
  }, [])
  return [affix, affixVisible];
}
